package com.skz;

import java.util.concurrent.*;

public class MyThreadPoolExecutor extends ThreadPoolExecutor {
    public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        System.out.println("线程" + Thread.currentThread().getId() + "执行结束");
    }

    @Override
    protected void terminated() {
        System.out.println("线程池关闭,释放资源");
    }

    public static void test() {
        MyThreadPoolExecutor myThreadPoolExecutor = new MyThreadPoolExecutor(10, 100, 0L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10), r -> {
            Thread thread = new Thread(r);
            thread.setName("mythread");
            return thread;
        }, new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i < 20; i++) {
            int num = i;
            myThreadPoolExecutor.execute(() -> {
                try {
                    //模拟耗时任务，触发拒绝策略
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务" + num + "被执行");
            });
        }
        myThreadPoolExecutor.shutdown();
    }
}
